package top.saplf.sileny.reader.network

import android.view.View
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.jakewharton.rxbinding2.view.RxView
import kotlinx.android.synthetic.main.item_network_article.view.*
import top.saplf.sileny.R
import top.saplf.sileny.net.gank.GankItem
import java.text.SimpleDateFormat

/**
 * @author saplf
 */
class NetworkArticleAdapter : BaseQuickAdapter<GankItem, BaseViewHolder>(R.layout.item_network_article) {
    companion object {
        private val dateFormatter: SimpleDateFormat by lazy {
            SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
        }
        private val targetFormatter: SimpleDateFormat by lazy {
            SimpleDateFormat("yyyy-MM-dd")
        }
    }

    var itemClickAction: ((GankItem) -> Unit)? = null

    override fun convert(helper: BaseViewHolder, item: GankItem) {
        helper.setText(R.id.title, item.desc)
                .setText(R.id.author, "作者：${item.who ?: "未知"}")
                .setText(R.id.time, "发布：${targetFormatter.format(dateFormatter.parse(item.createdAt))}")
        RxView.clicks(helper.itemView.rootView)
                .subscribe { itemClickAction?.invoke(item) }
        if (item.images?.isEmpty() ?: true) {
            helper.setVisible(R.id.picture, false)
        } else {
            helper.setVisible(R.id.picture, true)
            Glide.with(mContext)
                    .load(item.images?.get(0))
                    .into(helper.itemView.picture)
        }
    }
}